#coding:utf-8
'''
create on 2017-04-20

@author: sandy
'''


import json
import logging
ENCODING = u"UTF-8"

class Gate(object):
    def __init__(self,ip,port,sid,online):
        self.ip = ip
        self.port = port
        self.sid = sid
        self.online = online

class GateInfo(object):
    def __init__(self):
       self.gateMap = {}
        
    def parse(self,js):
        self.gateMap = {}
        jsObject = json.loads(js)
        for key in jsObject:
            j = jsObject[key]
            sid = j.get("sid")
            gate = self.gateMap.get(sid,None)
            if gate:
               gate.ip = j.get("ip")
               gate.port = j.get("port") 
               gate.sid = j.get("sid")
               gate.online = j.get("online")
            else:
                gate = Gate(j.get("ip"),j.get("port"),j.get("sid"),j.get("online"))
                self.gateMap[gate.sid] = gate

    def getSuitableGate(self):
        sids = self.gateMap.keys()
        if(len(sids) > 0):
            tmpSid = sids[0]
            for gate in self.gateMap:
                tmpGate = self.gateMap.get(tmpSid)
                curGate = self.gateMap.get(gate)
                if curGate.online < tmpGate.online:
                    tmpSid = curGate.sid
            return self.gateMap.get(tmpSid)
        else:
            return None

    def getSuitableGateJsonInfo(self):
        gate = self.getSuitableGate()
        sendDic = {}
        if gate != None:
            sendDic = {"ip":gate.ip,"port":gate.port}
        else:
            logging.debug("getSuitableGateJsonInfo gate is None")
        gateJson = json.dumps(sendDic).encode(ENCODING)
        return gateJson

instance = GateInfo()